<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
<script src="https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/autoload.js"></script>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/picture/pika.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/picture/pika.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="baidu-site-verification" content="code-LqqDM3vffE">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">


  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/2efd5eff.js","daovoice")
  daovoice('init', {
    app_id: "2efd5eff"
  });
  daovoice('update');
  </script>


<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"notspr.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":true,"color":"#ff7600","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":false,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="蓝鲸 Python 开发框架简介Python 开发框架是集成了蓝鲸系统功能，方便开发者可以快速在蓝鲸 PaaS 平台上开发 SaaS 的 Python 框架。 该开发框架基于 Django 框架架构，并在此基础上进行扩展，增加蓝鲸系统的特有功能， 例如：身份验证、ESB 调用及模板渲染等功能，以便开发者可以更专注于 SaaS 的逻辑开发。">
<meta property="og:type" content="article">
<meta property="og:title" content="初识蓝鲸开发框架">
<meta property="og:url" content="https://notspr.com/2020/04/24/bk-django-framework/index.html">
<meta property="og:site_name" content="Sapphire">
<meta property="og:description" content="蓝鲸 Python 开发框架简介Python 开发框架是集成了蓝鲸系统功能，方便开发者可以快速在蓝鲸 PaaS 平台上开发 SaaS 的 Python 框架。 该开发框架基于 Django 框架架构，并在此基础上进行扩展，增加蓝鲸系统的特有功能， 例如：身份验证、ESB 调用及模板渲染等功能，以便开发者可以更专注于 SaaS 的逻辑开发。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bkdocs-1252002024.file.myqcloud.com/ZH/5.1/%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97/SaaS%E5%BC%80%E5%8F%91/assets/usage-index.png">
<meta property="article:published_time" content="2020-04-23T17:34:52.000Z">
<meta property="article:modified_time" content="2020-12-02T17:36:56.244Z">
<meta property="article:author" content="Ryan Shu">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="Django">
<meta property="article:tag" content="蓝鲸">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bkdocs-1252002024.file.myqcloud.com/ZH/5.1/%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97/SaaS%E5%BC%80%E5%8F%91/assets/usage-index.png">

<link rel="canonical" href="https://notspr.com/2020/04/24/bk-django-framework/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>初识蓝鲸开发框架 | Sapphire</title>
  


  <script data-pjax>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?2907d577c8c6c2f7fe3843736d24280d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <!--pjax：防止跳转页面音乐暂停-->
  <script src="https://cdn.jsdelivr.net/npm/pjax@0.2.8/pjax.js"></script>
<link rel="alternate" href="/atom.xml" title="Sapphire" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Sapphire</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">興趣使然的博客</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/aboutme/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">82</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">34</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">40</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <a href="https://github.com/sususama5555" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://notspr.com/2020/04/24/bk-django-framework/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/picture/avatar.jpg">
      <meta itemprop="name" content="Ryan Shu">
      <meta itemprop="description" content="全栈 | 硬件 | 篮球 | 游戏">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Sapphire">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          初识蓝鲸开发框架
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-04-24 01:34:52" itemprop="dateCreated datePublished" datetime="2020-04-24T01:34:52+08:00">2020-04-24</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E8%93%9D%E9%B2%B8/" itemprop="url" rel="index"><span itemprop="name">蓝鲸</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E8%93%9D%E9%B2%B8/%E5%BC%80%E5%8F%91%E6%A1%86%E6%9E%B6/" itemprop="url" rel="index"><span itemprop="name">开发框架</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>9.1k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>8 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="蓝鲸-Python-开发框架简介"><a href="#蓝鲸-Python-开发框架简介" class="headerlink" title="蓝鲸 Python 开发框架简介"></a>蓝鲸 Python 开发框架简介</h2><p>Python 开发框架是集成了蓝鲸系统功能，方便开发者可以快速在蓝鲸 PaaS 平台上开发 SaaS 的 Python 框架。</p>
<p>该开发框架基于 Django 框架架构，并在此基础上进行扩展，增加蓝鲸系统的特有功能，</p>
<p>例如：身份验证、ESB 调用及模板渲染等功能，以便开发者可以更专注于 SaaS 的逻辑开发。</p>
<a id="more"></a>

<h2 id="目录结构说明"><a href="#目录结构说明" class="headerlink" title="目录结构说明"></a>目录结构说明</h2><h3 id="项目目录结构"><a href="#项目目录结构" class="headerlink" title="项目目录结构"></a>项目目录结构</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">- blueapps                    <span class="comment"># Python开发框架模块</span></span><br><span class="line">- blueking                    <span class="comment"># ESB调用模块</span></span><br><span class="line">- config                      <span class="comment"># 应用配置目录</span></span><br><span class="line">  - __init__.py               <span class="comment"># 应用 RUN_VER(社区版为open)、APP_CODE 和 SECRET_KEY 等配置</span></span><br><span class="line">  - dev.py                    <span class="comment"># 本地开发配置(开发团队共享)</span></span><br><span class="line">  - default.py                <span class="comment"># 全局配置</span></span><br><span class="line">  - prod.py                   <span class="comment"># 生产环境配置</span></span><br><span class="line">  - stag.py                   <span class="comment"># 预发布环境配置</span></span><br><span class="line">- home_application            <span class="comment"># Django 模板应用样例</span></span><br><span class="line">  - __init__.py</span><br><span class="line">  - admin.py</span><br><span class="line">  - urls.py</span><br><span class="line">  - models.py</span><br><span class="line">  - tests.py</span><br><span class="line">  - views.py</span><br><span class="line">  - templates                 <span class="comment"># Django 模板</span></span><br><span class="line">    - home_application</span><br><span class="line">      - contact.html          <span class="comment"># 联系我们页面</span></span><br><span class="line">      - dev_guide.html        <span class="comment"># 开发指引</span></span><br><span class="line">      - index_home.html       <span class="comment"># 首页</span></span><br><span class="line">- mako_templates              <span class="comment"># mako 公共模板文件</span></span><br><span class="line">  - base.mako                 <span class="comment"># mako 模板基础文件，其他的页面可以从这里继承</span></span><br><span class="line">- mako_application            <span class="comment"># mako 模板应用样例</span></span><br><span class="line">  - __init__.py</span><br><span class="line">  - admin.py</span><br><span class="line">  - urls.py</span><br><span class="line">  - models.py</span><br><span class="line">  - tests.py</span><br><span class="line">  - views.py</span><br><span class="line">  - mako_templates            <span class="comment"># 模板</span></span><br><span class="line">    - mako_application</span><br><span class="line">      - contact.html          <span class="comment"># 联系我们页面</span></span><br><span class="line">      - dev_guide.html        <span class="comment"># 开发指引</span></span><br><span class="line">      - index_home.html       <span class="comment"># 首页</span></span><br><span class="line">- static                      <span class="comment"># 公共静态文件</span></span><br><span class="line">  - js                        <span class="comment"># 公共 js</span></span><br><span class="line">    - csrftoken.js            <span class="comment"># CSRFTOKEN</span></span><br><span class="line">    - settings.js             <span class="comment"># 异常处理</span></span><br><span class="line">- templates                   <span class="comment"># 公共模板文件</span></span><br><span class="line">  - admin                     <span class="comment"># admin 模板文件</span></span><br><span class="line">    - base_site.html</span><br><span class="line">    - login.html</span><br><span class="line">  - base.html                 <span class="comment"># Django 模板基础文件，其他的页面可以从这里继承</span></span><br><span class="line">- manage.py                   <span class="comment"># Django 工程 manage</span></span><br><span class="line">- requirements.txt            <span class="comment"># 依赖的 python 包列表</span></span><br><span class="line">- settings.py                 <span class="comment"># Django 工程 settings</span></span><br><span class="line">- urls.py                     <span class="comment"># Django 工程主路由 URL 配置</span></span><br><span class="line">- wsgi.py                     <span class="comment"># WSGI配置</span></span><br><span class="line">- runtime.txt                 <span class="comment"># Python 版本配置文件，默认指向 Python</span></span><br></pre></td></tr></table></figure>

<h3 id="常用配置说明"><a href="#常用配置说明" class="headerlink" title="常用配置说明"></a>常用配置说明</h3><ul>
<li>App 基本信息</li>
</ul>
<p>在 config/<em>*init</em>*.py 可以查看 App 基本信息，请修改：APP_CODE、SECRET_KEY (用于 App 认证)和 BK_URL(蓝鲸 SaaS 平台的 URL)。RUN_VER 是当前 App 运行的 PaaS 版本，请不要修改。</p>
<ul>
<li>App 运行环境</li>
</ul>
<p>在 config/dev.py、config/stag.py、config/prod.py 中都有一个 RUN_MODE 的变量，用来标记 App 运营环境(DEVELOP：本地环境，STAGING：预发布环境，PRODUCT：正式环境)，请不要修改。</p>
<ul>
<li>日志级别和路径</li>
</ul>
<p>开发框架默认配置的日志级别是 INFO，你可以在 config/default.py 修改 LOG_LEVEL 变量，会对所有运行环境生效，你也可以单独修改 config/dev.py、config/stag.py、config/prod.py 文件，详情请参考“<a href="javascript:void(0)">日志使用</a>”。</p>
<p>你不需要关心线上运行环境的日志路径，这些开发框架已经自动帮你配置了；</p>
<p>本地的日志放在和项目根目录同一级的 logs 目录下，以 APP_CODE 命名的文件夹中，其中 {APP_CODE}-django.log 是应用日志，{APP_CODE}-celery.log 是 celery 日志，{APP_CODE}-component.log 是组件日志，{APP_CODE}-mysql.log 是数据库日志。</p>
<ul>
<li>数据库配置</li>
</ul>
<p>本地数据库配置请在 config/dev.py 修改 DATABASES 变量；多人合作开发建议在根目录下新建 local_settings.py 文件，并配置 DATABASES 变量，并且在版本控制中忽略 local_settings.py，这样的好处是防止多人合作开发时本地配置不一致导致代码冲突。</p>
<h2 id="开发环境搭建-Python"><a href="#开发环境搭建-Python" class="headerlink" title="开发环境搭建(Python)"></a>开发环境搭建(Python)</h2><h3 id="安装-Python-3-6"><a href="#安装-Python-3-6" class="headerlink" title="安装 Python(3.6)"></a>安装 Python(3.6)</h3><p>如果系统中已经安装有 Python2 版本，可以参考 Python 版本切换了解<a href="javascript:void(0)">Python3 与 Python2 并存的处理方案</a></p>
<h3 id="安装-MySQL-5-5-以上"><a href="#安装-MySQL-5-5-以上" class="headerlink" title="安装 MySQL(5.5 以上)"></a>安装 MySQL(5.5 以上)</h3><h3 id="安装-setuptools、pip-和项目依赖"><a href="#安装-setuptools、pip-和项目依赖" class="headerlink" title="安装 setuptools、pip 和项目依赖"></a>安装 setuptools、pip 和项目依赖</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip3 install -r requirements.txt</span><br></pre></td></tr></table></figure>

<blockquote>
<p>注意：由于依赖中存在 mysqlclient，该模块存在对 C 环境的依赖，开发者可以参考<a href="https://github.com/PyMySQL/mysqlclient-python#install" target="_blank" rel="noopener">项目主页</a>安装说明</p>
<p>此处不使用 PyMySQL 原因是该模块与 Django2.2 存在兼容<a href="https://github.com/PyMySQL/PyMySQL/issues/790" target="_blank" rel="noopener">问题</a></p>
</blockquote>
<h3 id="安装本地开发工具"><a href="#安装本地开发工具" class="headerlink" title="安装本地开发工具"></a>安装本地开发工具</h3><p>推荐使用 <a href="https://www.jetbrains.com/pycharm/download" target="_blank" rel="noopener">pycharm</a> 进行代码开发，使用 <a href="https://tortoisesvn.net/index.zh.html" target="_blank" rel="noopener">TortoiseSVN</a> 管理 SVN，使用 <a href="https://www.sourcetreeapp.com/" target="_blank" rel="noopener">SourceTree</a> 管理 GIT。</p>
<h3 id="安装-celery-需要使用后台任务的项目"><a href="#安装-celery-需要使用后台任务的项目" class="headerlink" title="安装 celery(需要使用后台任务的项目)"></a>安装 celery(需要使用后台任务的项目)</h3><p>安装项目依赖时会自动安装 celery==3.1.25 和 django-celery==3.2.1。目前 celery 支持 redis、rabbitmq 作为任务的消息队列，推荐使用 redis。</p>
<ul>
<li>mac 系统 redis 使用指南：</li>
</ul>
<p>安装指令 <code>brew install redis</code>；</p>
<p>启动指令 <code>redis-server</code>；</p>
<p>测试 redis 服务是否正常启动，<code>redis-cli</code> 尝试连接本地的 redis 服务。</p>
<ul>
<li>windows 系统 redis 使用指南</li>
</ul>
<p>下载安装地址：<a href="https://github.com/MicrosoftArchive/redis/releases" target="_blank" rel="noopener">https://github.com/MicrosoftArchive/redis/releases</a></p>
<p>点击安装目录下的 redis-server.exe 启动 redis 服务。</p>
<ul>
<li>配置项(在 config/dev.py 文件中修改消息队列配置)</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Celery 消息队列设置 RabbitMQ</span></span><br><span class="line"><span class="comment"># BROKER_URL = 'amqp://guest:guest@localhost:5672//'</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Celery 消息队列设置 Redis</span></span><br><span class="line">BROKER_URL = <span class="string">'redis://localhost:6379/0'</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>注意：由于 redis-3.0 及以后模块存在兼容问题，所以在安装 redis 模块是，请增加上版本控制要求<code>redis&gt;=2.10.6,&lt;3</code></p>
</blockquote>
<h3 id="配置-hosts"><a href="#配置-hosts" class="headerlink" title="配置 hosts"></a>配置 hosts</h3><p>本地需要修改 hosts 文件，添加如下内容：</p>
<blockquote>
<p><strong>注意</strong>： domain_name 应该修改为 PaaS 平台的域名</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1 appdev.`&#123;domain_name&#125;`</span><br></pre></td></tr></table></figure>

<h3 id="配置本地数据库"><a href="#配置本地数据库" class="headerlink" title="配置本地数据库"></a>配置本地数据库</h3><p>首先在 MySQL 命令行下创建数据库：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CREATE DATABASE  `&#123;APP_CODE&#125;` default charset utf8 COLLATE utf8_general_ci;</span><br></pre></td></tr></table></figure>

<p>然后配置本地数据库账号密码，需要找到 config/dev.py 中的 DATABASES 配置项，修改 USER 和 PASSWORD。</p>
<h3 id="初始化本地数据库"><a href="#初始化本地数据库" class="headerlink" title="初始化本地数据库"></a>初始化本地数据库</h3><p>在项目根目录下执行如下命令初始化本地数据库：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py migrate</span><br></pre></td></tr></table></figure>

<p>如果遇到错误，请先注释掉 config/default.py 的 INSTALLED_APPS 中的 APP 列表，执行命令后再去掉注释。</p>
<h3 id="启动项目"><a href="#启动项目" class="headerlink" title="启动项目"></a>启动项目</h3><p>在项目根目录下执行如下命令启动项目：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py runserver</span><br></pre></td></tr></table></figure>

<p>接着在浏览器访问 appdev.<code>{domain_name}</code> 就可以访问到项目首页了。</p>
<p><img data-src="https://bkdocs-1252002024.file.myqcloud.com/ZH/5.1/%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97/SaaS%E5%BC%80%E5%8F%91/assets/usage-index.png" alt="image-20190505204958140"></p>
<h2 id="新建-application"><a href="#新建-application" class="headerlink" title="新建 application"></a>新建 application</h2><p>在根目录下执行 django-admin startapp yourappname</p>
<p>进入 yourappname 目录，新增 urls.py</p>
<p>编写逻辑代码和路由配置代码</p>
<p>把 yourappname 加入 config/default.py 的 INSTALLED_APPS 中</p>
<h2 id="定义-model"><a href="#定义-model" class="headerlink" title="定义 model"></a>定义 model</h2><h3 id="在新建的-application-中-models-py-定义-model"><a href="#在新建的-application-中-models-py-定义-model" class="headerlink" title="在新建的 application 中 models.py 定义 model"></a>在新建的 application 中 models.py 定义 model</h3><p>官方文档：<a href="https://docs.djangoproject.com/en/2.2/topics/db/models/" target="_blank" rel="noopener">Django Models</a></p>
<h3 id="生成数据库变更文件"><a href="#生成数据库变更文件" class="headerlink" title="生成数据库变更文件"></a>生成数据库变更文件</h3><p>在项目根目录下执行如下命令：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py makemigrations yourappname</span><br></pre></td></tr></table></figure>

<p>执行成功后就会生成数据库变更文件，文件位于新建 APP 的 migrations 目录中。</p>
<h3 id="生效数据库变更"><a href="#生效数据库变更" class="headerlink" title="生效数据库变更"></a>生效数据库变更</h3><p>在项目根目录下执行如下命令：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py migrate yourappname</span><br></pre></td></tr></table></figure>

<blockquote>
<p><strong>注意</strong>：在把 yourappname 加入 config/default.py 的 INSTALLED_APPS 中之前，请先执行 python manage.py migrate 初始化数据库。</p>
</blockquote>
<h2 id="使用模板"><a href="#使用模板" class="headerlink" title="使用模板"></a>使用模板</h2><p>开发框架支持 Django、 Mako 两种模板渲染引擎，在 Django 工程下每个 App 维护自身的模板文件，以下以 APP_NAME 代表 Django APP 名称。</p>
<h3 id="Django-模板文件使用方式"><a href="#Django-模板文件使用方式" class="headerlink" title="Django 模板文件使用方式"></a>Django 模板文件使用方式</h3><p>请将你的 Django 模板文件 xxx.html 放在 <code>PROJECT_ROOT/APP_NAME/templates/</code> 目录底下，建议在 templates 底下在加上一层目录，取名为 APP_NAME，即最终模板文件存放路径为 <code>PROJECT_ROOT/APP_NAME/templates/APP_NAME</code>，这是为了避免在寻找模板文件的时候，出现覆盖的情况。</p>
<p>使用 Django 原生支持的 render 方法进行模板渲染。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">'APP_NAME/index.html'</span>, &#123;&#125;)</span><br></pre></td></tr></table></figure>

<p>render 函数接受三个参数：</p>
<ul>
<li>第一个参数 request 对象。</li>
<li>第二个参数 模板路径，从 APP templates 目录开始写起，此处对应的完整路径为 <code>PROJECT_ROOT/APP_NAME/templates/APP_NAME/index.html</code>，注意不要在前面加 ‘/‘，否则会被识别为绝对路径，找不到对应的模板。</li>
<li>第三个参数 传入的模板上下文，用于替换模板中的变量。</li>
</ul>
<blockquote>
<p>为什么 templates 目录底下还需要再加一层以 APP_NAME 命名的目录？ 假设 settings INSTALLED_APPS = (‘app1’, ‘app2’)，工程目录如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">PROJCET_ROOT</span><br><span class="line">|__ app1</span><br><span class="line">|__ __ templates</span><br><span class="line">|__ __ __ index.html</span><br><span class="line">...</span><br><span class="line">|__ app2</span><br><span class="line">|__ __ templates</span><br><span class="line">|__ __ __ index.html</span><br></pre></td></tr></table></figure>

<p>当我们在 app2.views 里使用 <code>render(request, &#39;index.html&#39;, {})</code> 语句进行渲染时，Django 框架默认以 INSTALLED_APPS 安装次序进行模板文件查找，这时候会匹配到 <code>app1/templates/index.html</code> 文件进行渲染，导致得到非预期的结果。所以推荐 <code>PROJECT_ROOT/APP_NAME/templates/APP_NAME</code> 这样的目录设计</p>
</blockquote>
<h3 id="Mako-模板文件使用方式"><a href="#Mako-模板文件使用方式" class="headerlink" title="Mako 模板文件使用方式"></a>Mako 模板文件使用方式</h3><p>Mako 模板文件使用方式大致与 Django 模板文件相同，唯一的区别就是是 Mako 模板文件放在 <code>PROJECT_ROOT/APP_NAME/mako_templates/</code> 目录底下，同样建议在 mako 底下在加上一层目录，取名为 APP_NAME，最终模板文件存放路径为 <code>PROJECT_ROOT/APP_NAME/mako_templates/APP_NAME</code>。</p>
<blockquote>
<p><strong>注意</strong>：出于安全原因，强烈建议用户使用 Django 模板替代 Mako 进行渲染，防止 XSS 攻击。</p>
</blockquote>
<h3 id="Template-Context-平台框架提供的模板变量"><a href="#Template-Context-平台框架提供的模板变量" class="headerlink" title="Template-Context 平台框架提供的模板变量"></a>Template-Context 平台框架提供的模板变量</h3><p>这里列举的模板变量，不需要用户在 render 模板时传入，可直接在模板文件中访问到，直接使用。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">context = &#123;</span><br><span class="line">    <span class="string">'STATIC_URL'</span>: settings.STATIC_URL,                    <span class="comment"># 本地静态文件访问</span></span><br><span class="line">    <span class="string">'APP_PATH'</span>: request.get_full_path(),                  <span class="comment"># 当前页面，主要为了 login_required 做跳转用</span></span><br><span class="line">    <span class="string">'RUN_MODE'</span>: settings.RUN_MODE,                        <span class="comment"># 运行模式</span></span><br><span class="line">    <span class="string">'APP_CODE'</span>: settings.APP_CODE,                        <span class="comment"># 在蓝鲸系统中注册的 "应用编码"</span></span><br><span class="line">    <span class="string">'SITE_URL'</span>: settings.SITE_URL,                        <span class="comment"># URL前缀</span></span><br><span class="line">    <span class="string">'REMOTE_STATIC_URL'</span>: settings.REMOTE_STATIC_URL,      <span class="comment"># 远程静态资源 url</span></span><br><span class="line">    <span class="string">'STATIC_VERSION'</span>: settings.STATIC_VERSION,            <span class="comment"># 静态资源版本号,用于指示浏览器更新缓存</span></span><br><span class="line">    <span class="string">'BK_URL'</span>: settings.BK_URL,                            <span class="comment"># 蓝鲸平台 URL</span></span><br><span class="line">    <span class="string">'USERNAME'</span>: username,                                 <span class="comment"># 用户名</span></span><br><span class="line">    <span class="string">'NICKNAME'</span>: nickname,                                 <span class="comment"># 用户昵称</span></span><br><span class="line">    <span class="string">'AVATAR_URL'</span>: avatar_url,                             <span class="comment"># 用户头像</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="静态资源使用规范"><a href="#静态资源使用规范" class="headerlink" title="静态资源使用规范"></a>静态资源使用规范</h2><ul>
<li>静态文件按模块划分，分别放在 Django 工程中每个对应 APP 的 static 目录下</li>
</ul>
<p>请将你的 Django 静态文件 xxx.js 和 xxx.css 放在 PROJECT_ROOT/APP_NAME/static/ 目录底下，建议在 static 底下在加上一层目录，取名为 APP_NAME，即最终模板文件存放路径为 PROJECT_ROOT/APP_NAME/static/APP_NAME[/js 或者/css]，这是为了避免在寻找静态文件的时候，出现覆盖的情况。</p>
<ul>
<li>修改静态文件后要手动运行 python manage.py collectstatic 命令来收集静态文件到根目录的 static 文件夹中。</li>
<li>settings 需要包含 STATIC_ROOT 配置。</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">STATIC_ROOT = os.path.join(BASE_DIR, <span class="string">'staticfiles'</span>)</span><br></pre></td></tr></table></figure>

<ul>
<li>框架已配置全局有效的静态目录，可以将所有公共使用的静态资源放置于此。</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">STATICFILES_DIRS = (</span><br><span class="line">    os.path.join(BASE_DIR, <span class="string">'static'</span>),</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>其中 BASE_DIR 是工程根目录路径。</p>
<h2 id="celery-使用"><a href="#celery-使用" class="headerlink" title="celery 使用"></a>celery 使用</h2><p>celery 是一个简单、灵活且可靠的，处理大量消息的分布式系统，并且提供维护这样一个系统的必需工具。 它是一个专注于实时处理的任务队列，同时也支持任务调度。</p>
<h3 id="打开-Celery-配置"><a href="#打开-Celery-配置" class="headerlink" title="打开 Celery 配置"></a>打开 Celery 配置</h3><p>在 config/default.py 中修改配置：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">IS_USE_CELERY = <span class="literal">True</span></span><br></pre></td></tr></table></figure>

<h3 id="添加-Celery-任务"><a href="#添加-Celery-任务" class="headerlink" title="添加 Celery 任务"></a>添加 Celery 任务</h3><p>在 app 底下创建 tasks.py 文件，添加 @task 任务：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> celery <span class="keyword">import</span> task</span><br><span class="line"></span><br><span class="line"><span class="meta">@task</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">mul</span><span class="params">(x, y)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> x * y</span><br></pre></td></tr></table></figure>

<p>如果 @task 任务函数不在 app/tasks.py 文件中，需要在 config/default.py 中添加配置：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">CELERY_IMPORTS = (</span><br><span class="line">    <span class="string">'testapp.tasks'</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<h3 id="启动异步任务服务-celery-worker"><a href="#启动异步任务服务-celery-worker" class="headerlink" title="启动异步任务服务 celery worker"></a>启动异步任务服务 celery worker</h3><p>在根目录执行：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py celery worker -l info</span><br></pre></td></tr></table></figure>

<h3 id="启动周期性任务服务-celery-beat"><a href="#启动周期性任务服务-celery-beat" class="headerlink" title="启动周期性任务服务 celery beat"></a>启动周期性任务服务 celery beat</h3><p>在根目录执行：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py celery beat -l info</span><br></pre></td></tr></table></figure>

<h3 id="添加周期任务"><a href="#添加周期任务" class="headerlink" title="添加周期任务"></a>添加周期任务</h3><p>进入 admin，在 DJCELERY-&gt;Periodic_tasks 表中添加一条记录。</p>
<h3 id="如何在平台部署时，自动启动-celery-进程"><a href="#如何在平台部署时，自动启动-celery-进程" class="headerlink" title="如何在平台部署时，自动启动 celery 进程"></a>如何在平台部署时，自动启动 celery 进程</h3><p>修改 IS_USE_CELERY = True，并在提测发布 SaaS 的时候，勾选使用 Celery 任务</p>
<h3 id="调整-celery-worker-并发数"><a href="#调整-celery-worker-并发数" class="headerlink" title="调整 celery worker 并发数"></a>调整 celery worker 并发数</h3><ul>
<li>CELERYD_CONCURRENCY 参数官方说明：<a href="http://docs.celeryproject.org/en/v2.2.4/configuration.html#celeryd-prefetch-multiplier" target="_blank" rel="noopener">官方文档</a></li>
<li>目前开发框架设置的 celery 并发数是 2，如需调整，有 2 种方法：</li>
</ul>
<p>1)在蓝鲸平台的 APP 环境变量新增 KEY 为 CELERYD_CONCURRENCY 的变量，并设置对应的值(调大前建议咨询平台维护同事)。</p>
<p>2)直接修改 APP 中的配置，即修改 config/default.py 文件中如下配置的默认值 2 为你想要设置的值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CELERYD_CONCURRENCY = os.getenv(<span class="string">'BK_CELERYD_CONCURRENCY'</span>, <span class="number">2</span>)</span><br></pre></td></tr></table></figure>

<h3 id="调整-celery-与-RabbitMQ-心跳包发送时间"><a href="#调整-celery-与-RabbitMQ-心跳包发送时间" class="headerlink" title="调整 celery 与 RabbitMQ 心跳包发送时间"></a>调整 celery 与 RabbitMQ 心跳包发送时间</h3><ul>
<li>BROKER_HEARTBEAT 参数官方说明：<a href="https://docs.celeryproject.org/en/3.1/configuration.html?#std:setting-BROKER_HEARTBEAT" target="_blank" rel="noopener">官方文档</a></li>
<li>目前开发框架设置的 BROKER_HEARTBEAT 发送时间是 60，即每 60 秒发送一个心跳包，如需调整，有以下方法：</li>
</ul>
<p>直接修改 APP 中的配置，即在 config/default.py 文件中添加相应配置，框架默认的配置会被覆盖。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># CELERY与RabbitMQ增加60秒心跳设置项</span></span><br><span class="line">BROKER_HEARTBEAT = <span class="number">60</span></span><br></pre></td></tr></table></figure>

<h2 id="日志使用"><a href="#日志使用" class="headerlink" title="日志使用"></a>日志使用</h2><ul>
<li>日志相关配置方式复用 Django 的配置方式：<a href="https://docs.djangoproject.com/en/2.2/topics/logging/#using-logging" target="_blank" rel="noopener">官方文档</a></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> logging</span><br><span class="line">logger = logging.getLogger(<span class="string">'app'</span>)       <span class="comment"># 普通日志</span></span><br><span class="line">logger_celery = logging.getLogger(<span class="string">'celery'</span>)   <span class="comment"># celery日志</span></span><br><span class="line">logger.error(<span class="string">'log your info here.'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 第二种方式</span></span><br><span class="line"><span class="keyword">from</span> blueapps.util.logger <span class="keyword">import</span> logger         <span class="comment"># 普通日志</span></span><br><span class="line"><span class="keyword">from</span> blueapps.util.logger <span class="keyword">import</span> logger_celery  <span class="comment"># celery日志</span></span><br><span class="line">logger.error(<span class="string">'log your info here.'</span>)</span><br></pre></td></tr></table></figure>

<ul>
<li>日志输出路径：</li>
</ul>
<p>本地输出路径在和项目根目录平级的 logs 目录下。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">- PROJCET_ROOT</span><br><span class="line">- logs</span><br><span class="line">    - APP_CODE</span><br><span class="line">        - APP_CODE-celery.log</span><br><span class="line">        - APP_CODE-component.log</span><br><span class="line">        - APP_CODE-django.log</span><br><span class="line">        - APP_CODE-mysql.log</span><br></pre></td></tr></table></figure>

<ul>
<li>日志级别配置：</li>
</ul>
<p>日志级别默认是 INFO，如需修改：</p>
<ol>
<li><p>所有环境下的日志级别，请在 config/default.py 对应位置修改日志级别：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">LOG_LEVEL = <span class="string">"DEBUG"</span></span><br><span class="line"><span class="comment"># load logging settings</span></span><br><span class="line">LOGGING = get_logging_config_dict(locals())</span><br></pre></td></tr></table></figure>
</li>
<li><p>如果只希望针对特定环境进行日志级别设置，则在对应环境配置文件（ config/prod.py（只影响生产环境）、config/stag.py（只影响预发布环境）、config/dev.py（只影响预本地开发环境））中取消对应代码注释并修改日志级别：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 自定义本地环境日志级别</span></span><br><span class="line"><span class="keyword">from</span> blueapps.conf.log <span class="keyword">import</span> set_log_level <span class="comment"># noqa</span></span><br><span class="line">LOG_LEVEL = <span class="string">"DEBUG"</span></span><br><span class="line">LOGGING = set_log_level(locals())</span><br></pre></td></tr></table></figure>

<p><strong>注意</strong>: 这种修改方式依赖 blueapps 版本 &gt;= 3.3.1。</p>
</li>
</ol>
<p>其中，不同配置的含义如下：</p>
<ol>
<li>DEBUG：用于调试目的的底层系统信息</li>
<li>INFO：普通的系统信息</li>
<li>WARNING：表示出现一个较小的问题。</li>
<li>ERROR：表示出现一个较大的问题。</li>
<li>CRITICAL：表示出现一个致命的问题。</li>
</ol>
<h2 id="异常处理"><a href="#异常处理" class="headerlink" title="异常处理"></a>异常处理</h2><p>为了减少代码中判断函数调用的判断逻辑，蓝鲸开发框架提出，开发者应该在异常处直接抛出异常，通过 Django 中间件特性来处理该异常。</p>
<h3 id="使用样例"><a href="#使用样例" class="headerlink" title="使用样例"></a>使用样例</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> blueapps.core.exceptions <span class="keyword">import</span> ParamValidationError</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">your_view_func</span><span class="params">(request)</span>:</span></span><br><span class="line">  form = your_form(request.POST)</span><br><span class="line">  <span class="keyword">if</span> <span class="keyword">not</span> form.is_valid():</span><br><span class="line">    <span class="keyword">raise</span> ParamValidationError(<span class="string">u'参数验证失败,请确认后重试'</span>)</span><br><span class="line">  <span class="comment"># do something you want</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p><strong>注意</strong>：此处只是一个简单的示例。我们强烈的建议开发者应该在任何有错误的地方直接抛出异常，而非返回错误，由上层逻辑处理。</p>
</blockquote>
<h3 id="异常类型介绍"><a href="#异常类型介绍" class="headerlink" title="异常类型介绍"></a>异常类型介绍</h3><p>蓝鲸开发框架异常类主要分为两类：客户端异常及服务端异常，分别对应由于客户端请求引起的错误和后台服务引起的错误。开发者可以根据引起错误的场景来选择需要抛出的异常。</p>
<ul>
<li>异常类所在命名空间<ul>
<li>blueapps.core.exceptionsplainplainplainplainplainplainplainplainplainplainplainplainplainplainplainplainplainplain</li>
</ul>
</li>
<li>服务端异常</li>
</ul>
<table>
<thead>
<tr>
<th>错误类</th>
<th>说明</th>
<th>http 状态码</th>
<th>返回错误码</th>
<th>场景举例</th>
</tr>
</thead>
<tbody><tr>
<td>DatabaseError</td>
<td>数据库异常</td>
<td>501</td>
<td>50110</td>
<td>更新数据库记录失败</td>
</tr>
<tr>
<td>ApiNetworkError</td>
<td>网络异常导致远程服务失效</td>
<td>503</td>
<td>50301</td>
<td>请求第三方接口由于网络连接问题导致失败</td>
</tr>
<tr>
<td>ApiResultError</td>
<td>远程服务请求结果异常</td>
<td>503</td>
<td>50302</td>
<td>请求第三方结果返回 result 结果是 false</td>
</tr>
<tr>
<td>ApiNotAcceptable</td>
<td>远程服务返回结果格式异常</td>
<td>503</td>
<td>50303</td>
<td>第三方接口返回 xml 格式结果，但预期返回 json 格式</td>
</tr>
</tbody></table>
<ul>
<li>客户端异常</li>
</ul>
<table>
<thead>
<tr>
<th>错误类</th>
<th>说明</th>
<th>http 状态码</th>
<th>返回错误码</th>
<th>场景举例</th>
</tr>
</thead>
<tbody><tr>
<td>ParamValidationError</td>
<td>参数验证失败</td>
<td>400</td>
<td>40000</td>
<td>期待为整形的参数，用户提供了一个字符参数</td>
</tr>
<tr>
<td>ParamRequired</td>
<td>请求参数缺失</td>
<td>400</td>
<td>40001</td>
<td>期待的参数找不到</td>
</tr>
<tr>
<td>RioVerifyError</td>
<td>登陆请求经智能网关检测失败</td>
<td>401</td>
<td>40101</td>
<td>用户登录验证</td>
</tr>
<tr>
<td>BkJwtVerifyError</td>
<td>登陆请求经 JWT 检测失败</td>
<td>401</td>
<td>40102</td>
<td>用户登录验证</td>
</tr>
<tr>
<td>AccessForbidden</td>
<td>登陆失败</td>
<td>403</td>
<td>40301</td>
<td>用户身份验证失败</td>
</tr>
<tr>
<td>RequestForbidden</td>
<td>请求拒绝</td>
<td>403</td>
<td>40320</td>
<td>用户企图操作没有权限的任务</td>
</tr>
<tr>
<td>ResourceLock</td>
<td>请求资源被锁定</td>
<td>403</td>
<td>40330</td>
<td>用户企图操作一个已经锁定的任务</td>
</tr>
<tr>
<td>ResourceNotFound</td>
<td>找不到请求的资源</td>
<td>404</td>
<td>40400</td>
<td>找不到用户请求的某个指定 ID 的 model</td>
</tr>
<tr>
<td>MethodError</td>
<td>请求方法不支持</td>
<td>405</td>
<td>40501</td>
<td>用户发送的请求不在预期范围内</td>
</tr>
</tbody></table>
<hr>
<p>参考链接：<br><a href="https://bk.tencent.com/docs/document/5.1/19/576" target="_blank" rel="noopener">腾讯蓝鲸开发框架 2.0 使用说明</a></p>

    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Ryan Shu
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://notspr.com/2020/04/24/bk-django-framework/" title="初识蓝鲸开发框架">https://notspr.com/2020/04/24/bk-django-framework/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/picture/weixin.png">
            <span class="icon">
              <i class="fab fa-weixin"></i>
            </span>

            <span class="label">WeChat</span>
          </a>
        </div>

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
              <a href="/tags/Django/" rel="tag"><i class="fa fa-tag"></i> Django</a>
              <a href="/tags/%E8%93%9D%E9%B2%B8/" rel="tag"><i class="fa fa-tag"></i> 蓝鲸</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/04/23/go-basis-sequence/" rel="prev" title="Go语言之顺序编程">
      <i class="fa fa-chevron-left"></i> Go语言之顺序编程
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/04/29/bk-django-framework-advanced/" rel="next" title="蓝鲸开发框架进阶">
      蓝鲸开发框架进阶 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#蓝鲸-Python-开发框架简介"><span class="nav-number">1.</span> <span class="nav-text">蓝鲸 Python 开发框架简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#目录结构说明"><span class="nav-number">2.</span> <span class="nav-text">目录结构说明</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#项目目录结构"><span class="nav-number">2.1.</span> <span class="nav-text">项目目录结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常用配置说明"><span class="nav-number">2.2.</span> <span class="nav-text">常用配置说明</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开发环境搭建-Python"><span class="nav-number">3.</span> <span class="nav-text">开发环境搭建(Python)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#安装-Python-3-6"><span class="nav-number">3.1.</span> <span class="nav-text">安装 Python(3.6)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#安装-MySQL-5-5-以上"><span class="nav-number">3.2.</span> <span class="nav-text">安装 MySQL(5.5 以上)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#安装-setuptools、pip-和项目依赖"><span class="nav-number">3.3.</span> <span class="nav-text">安装 setuptools、pip 和项目依赖</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#安装本地开发工具"><span class="nav-number">3.4.</span> <span class="nav-text">安装本地开发工具</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#安装-celery-需要使用后台任务的项目"><span class="nav-number">3.5.</span> <span class="nav-text">安装 celery(需要使用后台任务的项目)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#配置-hosts"><span class="nav-number">3.6.</span> <span class="nav-text">配置 hosts</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#配置本地数据库"><span class="nav-number">3.7.</span> <span class="nav-text">配置本地数据库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#初始化本地数据库"><span class="nav-number">3.8.</span> <span class="nav-text">初始化本地数据库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#启动项目"><span class="nav-number">3.9.</span> <span class="nav-text">启动项目</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#新建-application"><span class="nav-number">4.</span> <span class="nav-text">新建 application</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#定义-model"><span class="nav-number">5.</span> <span class="nav-text">定义 model</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#在新建的-application-中-models-py-定义-model"><span class="nav-number">5.1.</span> <span class="nav-text">在新建的 application 中 models.py 定义 model</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#生成数据库变更文件"><span class="nav-number">5.2.</span> <span class="nav-text">生成数据库变更文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#生效数据库变更"><span class="nav-number">5.3.</span> <span class="nav-text">生效数据库变更</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用模板"><span class="nav-number">6.</span> <span class="nav-text">使用模板</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Django-模板文件使用方式"><span class="nav-number">6.1.</span> <span class="nav-text">Django 模板文件使用方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Mako-模板文件使用方式"><span class="nav-number">6.2.</span> <span class="nav-text">Mako 模板文件使用方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Template-Context-平台框架提供的模板变量"><span class="nav-number">6.3.</span> <span class="nav-text">Template-Context 平台框架提供的模板变量</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#静态资源使用规范"><span class="nav-number">7.</span> <span class="nav-text">静态资源使用规范</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#celery-使用"><span class="nav-number">8.</span> <span class="nav-text">celery 使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#打开-Celery-配置"><span class="nav-number">8.1.</span> <span class="nav-text">打开 Celery 配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加-Celery-任务"><span class="nav-number">8.2.</span> <span class="nav-text">添加 Celery 任务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#启动异步任务服务-celery-worker"><span class="nav-number">8.3.</span> <span class="nav-text">启动异步任务服务 celery worker</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#启动周期性任务服务-celery-beat"><span class="nav-number">8.4.</span> <span class="nav-text">启动周期性任务服务 celery beat</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加周期任务"><span class="nav-number">8.5.</span> <span class="nav-text">添加周期任务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#如何在平台部署时，自动启动-celery-进程"><span class="nav-number">8.6.</span> <span class="nav-text">如何在平台部署时，自动启动 celery 进程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#调整-celery-worker-并发数"><span class="nav-number">8.7.</span> <span class="nav-text">调整 celery worker 并发数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#调整-celery-与-RabbitMQ-心跳包发送时间"><span class="nav-number">8.8.</span> <span class="nav-text">调整 celery 与 RabbitMQ 心跳包发送时间</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#日志使用"><span class="nav-number">9.</span> <span class="nav-text">日志使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#异常处理"><span class="nav-number">10.</span> <span class="nav-text">异常处理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#使用样例"><span class="nav-number">10.1.</span> <span class="nav-text">使用样例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#异常类型介绍"><span class="nav-number">10.2.</span> <span class="nav-text">异常类型介绍</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Ryan Shu"
      src="/picture/avatar.jpg">
  <p class="site-author-name" itemprop="name">Ryan Shu</p>
  <div class="site-description" itemprop="description">全栈 | 硬件 | 篮球 | 游戏</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">40</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">34</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">82</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/sususama5555" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sususama5555" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:876324872@qq.com" title="E-Mail → mailto:876324872@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/5330189327" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;5330189327" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://steamcommunity.com/profiles/76561198294148424/" title="steam → https:&#x2F;&#x2F;steamcommunity.com&#x2F;profiles&#x2F;76561198294148424&#x2F;" rel="noopener" target="_blank"><i class="fab fa-steam fa-fw"></i>steam</a>
      </span>
      <span class="links-of-author-item">
        <a href="/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-rss fa-fw"></i>RSS</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://ddoudou.xyz/" title="http:&#x2F;&#x2F;ddoudou.xyz" rel="noopener" target="_blank">豆豆的博客</a>
        </li>
    </ul>
  </div>

      </div>

      <!-- 音乐播放器 -->
      
           <div>
              <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="210" height="110" src="//music.163.com/outchain/player?type=2&id=4226232&auto=1&height=66"></iframe>
           </div>
      

      <!-- 滚动条 -->
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">粤ICP备20063016号-2 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ryan Shu</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">180k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">2:44</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  
  <script data-pjax>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  

    </div>
</body>
</html>
